package com.example.back.controller;

import com.example.back.constants.Login;
import com.example.back.dto.resp.LoginResp;
import com.example.back.dto.req.LoginReq;
import com.example.back.service.SysAdminService;
import com.example.common.support.Result;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.image.BufferedImage;

@RestController
@Api(tags = "用户登录")
@RequestMapping("/api/login")
public class LoginController {

    @Resource
    private DefaultKaptcha captchaProducer;

    @Resource
    private SysAdminService sysAdminService;

    @Resource
    private RedisTemplate redisTemplate;


    @ApiOperation(value = "获取验证码", notes = "获取验证码")
   @RequestMapping(value = "/CreateValidateImg",method = RequestMethod.GET)
    @ResponseBody  //返回字符串到页面
    public void  hello(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)  throws Exception{

       byte[] captchaOutputStream = null;
       ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
       try {

           String key = httpServletRequest.getParameter("key");
           //生产验证码字符串并保存到session中
           String verifyCode = captchaProducer.createText();
           redisTemplate.opsForValue().set(Login.VALIDATE_ID +key,verifyCode,60*10, TimeUnit.SECONDS);
           //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
           BufferedImage challenge = captchaProducer.createImage(verifyCode);
           ImageIO.write(challenge, "jpg", imgOutputStream);
       } catch (IllegalArgumentException e) {
           httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
           return;
       }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
       captchaOutputStream = imgOutputStream.toByteArray();
       httpServletResponse.setHeader("Cache-Control", "no-store");
       httpServletResponse.setHeader("Pragma", "no-cache");
       httpServletResponse.setDateHeader("Expires", 0);
       httpServletResponse.setContentType("image/jpeg");
       ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
       responseOutputStream.write(captchaOutputStream);
       responseOutputStream.flush();
       responseOutputStream.close();
    }


    @ApiOperation(value = "用户登录", notes = "用户登录")
    @PostMapping(value = "/logincommit")
    public Result<LoginResp> login( @RequestBody LoginReq req){
        return Result.success(sysAdminService.Login(req));
    }

}
